import random

from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.verifications.serializers import SmsCodeSerializer
from libs.captcha.captcha import captcha


# 生成图片验证码
class ImageCodeView(APIView):
    def get(self, request, image_code_id):
        # 调用模块，生成文本、图片
        text, image_data = captcha.generate_captcha()
        # 在控制台打印
        print("图片验证码：%s " % text)

        # 获取redis对象
        redis_conn = get_redis_connection("code")
        # 将图片验证码存放到redis中
        redis_conn.setex("image_code_%s" % image_code_id, 300, text)

        # 获取响应体对象
        response = HttpResponse(image_data)
        # 设置返回的响应体类型
        response['Content-Type'] = "image/jpg"

        return response


# 发送短信验证码
class SmsCodeView(GenericAPIView):
    # 指定序列化器类
    serializer_class = SmsCodeSerializer

    def get(self, request, mobile):
        # 获取redis对象
        redis_connection = get_redis_connection("code")

        #获取并判断短信验证码是否频繁发送
        reids_sms_expiry=redis_connection.get("sms_code_expiry_%s" % mobile)
        if  reids_sms_expiry:
            return Response(data={"errmsg":"短信验证码频繁发送"},status=status.HTTP_400_BAD_REQUEST)

        # 获取查询参数
        query_params = request.query_params

        # 反序列化
        serializer = self.get_serializer(data=query_params)
        # 校验
        serializer.is_valid(raise_exception=True)

        # 生成短信验证码
        sms_code = "%06d" % random.randint(1, 999999)
        #调用发送短信验证码函数
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(sms_code)

        # 短信验证码在控制台打印
        print("短信验证码：%s" % sms_code)

        # 将短信验证码存放到redis中
        redis_connection.setex("sms_code_%s" % mobile, 300, sms_code)
        #设置可再发送短信验证码的间隔
        redis_connection.setex("sms_code_expiry_%s" % mobile, 60, True)

        return Response(status=status.HTTP_200_OK)
